package com.hilda.HTMLParserTesting.tagSoup;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXSource;

import org.ccil.cowan.tagsoup.Parser;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

/**
 * TagSoup uses SAX, a low-level librarie for parser web... It is very complex
 * and I think not implemented on Android Java SDK
 * 
 * @author olidroide
 * 
 */
public class HildaTagSoup {
	private Context mContext;
	private String URL;

	public HildaTagSoup(Context c) {
		Log.i("crawDroid", "Start HildaTagSoup parser");
		mContext = c;
	}

	public void parse(String url) {
		URL = url;
		DowloadWebTask dowloadWebTask = new DowloadWebTask();
		dowloadWebTask.execute();
	}

	private class DowloadWebTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			Log.i("crawDroid", "Start HildaTagSoup AsyncTask");

			URL url;

			try {

				url = new URL(URL);

				XMLReader reader = new Parser();
				reader.setFeature(Parser.namespacesFeature, false);
				reader.setFeature(Parser.namespacePrefixesFeature, false);

				Transformer transformer = TransformerFactory.newInstance()
						.newTransformer();

				DOMResult domResult = new DOMResult();
				transformer
						.transform(
								new SAXSource(reader, new InputSource(url
										.openStream())), domResult);

				Node resultNode = domResult.getNode();
				
				Log.v("crawDroid", "Nodes HildaTagSoup: "
						+ domResult.getNode().getNodeName());

			} catch (MalformedURLException e) {
				Log.e("crawDroid", e.getMessage());
			} catch (SAXNotRecognizedException e) {
				Log.e("crawDroid", e.getMessage());
			} catch (SAXNotSupportedException e) {
				Log.e("crawDroid", e.getMessage());
			} catch (TransformerException e) {
				Log.e("crawDroid", e.getMessage());
			} catch (IOException e) {
				Log.e("crawDroid", e.getMessage());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.i("crawDroid", "Finish HildaTagSoup AsyncTask");
			super.onPostExecute(result);
		}
	}

}
